
import { storeApi, commonApi } from '../../api/index';
import { toast, confirm } from "../../utils/modal"
import { getCurrentDate } from "../../utils/util"
// 获取app
var app = getApp();
Page({
  data: {
    filesHost: app.globalData.filesHost,
    pageParam: {
      page: 1,
      page_size: 10
    },
    storeInfo: {},
    typeList: [],
    selectType: {},
    colorList: [],
    colorListArr: [], //保留一份原来的
    selectColor: {},
    areaList: [],
    selectArea: {},
    showStep1: true,
    dateList: [],
    selectDate: {},
    timeList: [],
    selectTime: {},
    costTime: {
      cost_time_min: null,
      cost_time_max: null
    }, // 预估时间
    costPrice: {
      discount_amount: null, // 优惠价格
      final_amount: null, //最终价
      ori_total_amount: null  //原始价格
    }, // 预估价格
    scrollTop: 0,
    showLoginTipPopup: false,
  },
  async getData() {
    try {
      const res = await storeApi.queryStoreList(this.data.pageParam)
      this.setData({
        storeInfo: res.list[0],
      })
      this.getProjectList()
    } catch (e) { }
  },
  async getProjectList() {
    try {
      const storeInfo = this.data.storeInfo
      const res = await storeApi.queryProjectList({ ran_store_id: storeInfo.id })
      this.setData({
        areaList: res.hair_region_list.list,
        colorList: res.hairdye_color_list.list,
        colorListArr: res.hairdye_color_list.list,
        typeList: res.hairdye_type_list.list,
      })
    } catch (e) { }
  },
  async getBusinessDateList() {
    try {
      const storeInfo = this.data.storeInfo
      const currentDate = getCurrentDate()
      const res = await storeApi.queryBusinessDateList({
        ran_store_id: storeInfo.id
      })
      this.setData({
        dateList: res.list || [],
      })
      if (res?.list?.length) {
        this.setData({
          selectDate: {
            index: 0,
            date_cn: res.list[0].date_cn,
            date: res.list[0].date,
          }
        })
        this.getTimeBlockList(res.list.length ? res.list[0].date : currentDate)
      } else {
        toast('该门店暂无可预约时间，请联系店员')
      }
    } catch (e) { }
  },
  async getTimeBlockList(data, noScroll) {
    try {
      let isNoScroll = noScroll || false
      const storeInfo = this.data.storeInfo
      const res = await storeApi.queryTimeBlockList({
        ran_store_id: storeInfo.id,
        date: data
      })
      this.setData({
        timeList: res.list,
      })
      if (res.list.length === 0) {
        toast('该门店暂无可预约时间，请联系店员')
        return
      }
      if(isNoScroll) return
      const currentTimeIdx = res.list.findIndex(item => item.is_expired == 0)
      if (currentTimeIdx > 0) {
        this.scrollToItem(currentTimeIdx);
      } else {
        this.setData({
          scrollTop: 0
        });
      }

    } catch (e) { }
  },
  scrollToItem(index) {
    // 滚动到当前时间
    let distanceFromTop = 0
    const queryTime = wx.createSelectorQuery();
    queryTime.select('#book-time').boundingClientRect((res) => {
      if (res) {
        distanceFromTop = res.top; // 距离页面顶部的距离
        console.log('距离顶部的距离:', distanceFromTop);
      }
    }).exec();
    const query = wx.createSelectorQuery();
    query.select(`#bookTimeItem-${index}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec((res) => {
      if (res[0] && res[1]) {
        const itemTop = res[0].top;
        const scrollOffset = res[1].scrollTop;
        this.setData({
          scrollTop: scrollOffset + itemTop - distanceFromTop
          // scrollTop: scrollOffset + itemTop 
        });
      }
    });
  },
  async getProjectTime() {
    try {
      const { selectType, selectColor, selectArea } = this.data
      const res = await storeApi.getProjectTime({
        ran_store_hairdye_type_id: selectType.id,
        ran_store_hairdye_color_id: selectColor.id,
        ran_store_hair_region_id: selectArea.id
      })
      this.setData({
        costTime: res,
      })
    } catch (e) { }
  },
  async getProjectPrice() {
    try {
      const { selectType, selectColor, selectArea } = this.data
      const res = await storeApi.getProjectPrice({
        ran_store_hairdye_type_id: selectType.id,
        ran_store_hairdye_color_id: selectColor.id,
        ran_store_hair_region_id: selectArea.id,
        buy_vip : 1 //写死为1
      })
      this.setData({
        costPrice: res,
      })
    } catch (e) { }
  },

  onSelectType(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectType: {
        id: target.id,
        text: target.text,
        desc: target.desc,
      },
    });
    let colorList = this.data.colorListArr
    if(target.text === '低敏染膏'){
      colorList = colorList.filter(item => item.name !== '葡萄红' );
      console.log('colorList', colorList)
      this.setData({
        colorList: colorList,
      });
    }else{
      this.setData({
        colorList: colorList,
      });
    }
  },
  onSelectColor(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectColor: {
        id: target.id,
        text: target.text,
        desc: target.desc,
      },
    });
  },
  onSelectArea(e) {
    const target = e.currentTarget.dataset;
    this.setData({
      selectArea: {
        id: target.id,
        text: target.text,
        desc: target.desc,
      },
    });
  },
  onSelectDate(e) {
    const target = e.currentTarget.dataset;
    if (target.disabled) {
      return;
    }
    this.setData({
      selectDate: {
        index: target.idx,
        date_cn: target.date_cn,
        date: target.date,
      },
      selectTime: {}
    });
    this.getTimeBlockList(target.date)
  },
  onSelectTime(e) {
    const target = e.currentTarget.dataset;
    if (target.disabled) {
      return;
    }
    this.setData({
      selectTime: {
        index: target.idx,
        time: target.time,
        start_at: target.start_at,
      },
    });
  },
  onReselect() {
    this.setData({
      showStep1: true,
    });
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0,
    });
  },
  toStep2() {
    const { selectType, selectColor, selectArea } = this.data
    if (selectType.id && selectColor.id && selectArea.id) {
      this.setData({
        showStep1: false,
      });
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0,
      });
      wx.setNavigationBarTitle({
        title: '预约步骤2/2',
      });
      this.getProjectTime() // 获取预估时间
      this.getProjectPrice() // 获取预估价格
      this.getBusinessDateList() // 获取店铺营业时间
    }
  },
  async createReservationOrder() {
    try {
      const { storeInfo, selectType, selectColor, selectArea, selectTime, userInfo } = this.data
       console.log(userInfo)
      if(userInfo?.employee_info?.id){
        // 店员身份跳代客预约
        confirm('您是店员，请通过代客预约下单', function (msg) {
          if (msg) {
            wx.redirectTo({
              url: `/pages/book-for-customer/book-for-customer`,
            });
          }
        });
      } else {
        const res = await storeApi.createReservationOrder({
          ran_store_id: storeInfo.id,
          ran_store_hairdye_type_id: selectType.id,
          ran_store_hairdye_color_id: selectColor.id,
          ran_store_hair_region_id: selectArea.id,
          start_at: selectTime.start_at,
          // phone: userInfo?.phone ?? '',
        })
        if (res?.id) {
          wx.redirectTo({
            url: `/pages/book-success/book-success?id=${res?.id}`,
          });
        }
      }
    } catch (err) {
      // 时间块被抢走，刷新时间
      if (err.error_code == 5001) {
        this.getTimeBlockList(this.data.selectDate.date , true)
        this.setData({
          selectTime: {},
        });
      }
    }
  },
  async onBook() {
    const { selectDate, selectTime, userInfo } = this.data
    if (selectDate.index >= 0 && selectTime.index >= 0) {
      if (!!userInfo?.phone) {
        this.createReservationOrder();
      } else {
        this.setData({
          showLoginTipPopup: true,
        });
      }
    }
  },
  cancelLoginTipPopup(event) {
    let val = event.detail;
    console.log(val.phoneNumber)
    this.setData({
      showLoginTipPopup: false,
      userInfo: {
        ...this.data.userInfo,
        phone: val.phoneNumber
      },
    });
    this.getUserInfo()
    console.log(this.data.userInfo)
  },
  async getUserInfo() {
    try {
      let res = res = await commonApi.getUserInfo()
      this.setData({
        userInfo: res,
      })
    } catch (e) { }
  },
  goCall(e) {
    const phoneNumber = this.data.storeInfo.phone
    wx.makePhoneCall({
      phoneNumber
    });
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: '预约步骤1/2',
    });
    this.getData()
    this.getUserInfo()
  },
  onReady() { },
  onShow() {
    // wx.setNavigationBarTitle({
    //   title: '预约步骤1/2',
    // });
    // this.setData({
    //   showStep1: true,
    //   selectType: {},
    //   selectColor: {},
    //   selectArea: {},
    //   showStep1: true,
    //   selectDate: {},
    //   selectTime: {},
    // });
    // this.getData()
  },
  onHide() { },
  onUnload() { },
  onPullDownRefresh() { },
  onReachBottom() { },
  onShareAppMessage() { 
    return {
      title: '频繁染白发，就找染博士',
      imageUrl:
        'https://ranboss.oss-cn-beijing.aliyuncs.com/ranstore/share.png',
    };
  },
});
